package com.liyuan.help_e.service.impl;

import com.liyuan.help_e.model.Page;
import com.liyuan.help_e.service.PageService;
import com.liyuan.help_e.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;

@Service
public class PageServiceImpl implements PageService {
    @Autowired
    QuestionService questionService;
    @Override
    public Page paging(Integer page, Integer size, Integer sum) {
        return getPage(page,size,sum);
    }

    @Override
    public Page pagingByQuestionsUserId(Integer currentPage, int size, Integer id) {
        return getPage(currentPage,size,questionService.sumByUserId(id));
    }


    private Page getPage(Integer currentPage, Integer size, Integer sum) {
        Page page = new Page();
        page.setCurrentPage(currentPage);
        page.setLastPage(sum % size == 0 ? sum / size : sum / size + 1);
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(currentPage);
        int totalPage;
        if (sum % size == 0) {
            totalPage = sum / size;
        } else {
            totalPage = sum / size + 1;
        }
        for (int i = 1; i <= size / 2; i++) {
            if (currentPage - i > 0) {
                linkedList.addFirst(currentPage - i);
            }
            if (currentPage + i <= totalPage) {
                linkedList.addLast(currentPage + i);
            }
        }
        page.setPages(linkedList);
        return page;
    }

}
